package com.biyao.core.config;



import java.util.HashMap;
import java.util.Map;

/**
 * Created by 郑浩 on 2017/8/11.
 * 数据库切换类，在程序运行过程中对数据库动态的切换工具类
 */

public class DataSourceSwitch {
    volatile private static DataSourceSwitch instance;

    private DataSourceSwitch() {
    }

    public static DataSourceSwitch getInstance() {
        try {
            if (instance != null) {

            } else {
                Thread.sleep(300);
                synchronized (DataSourceSwitch.class) {
                    if (instance == null) {
                        instance = new DataSourceSwitch();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return instance;
    }

    public void SetDataSourceSwitch(String key, String ip, String datatype, String username, String pas, int port, String driver) {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put(DataSourceContextHolder.DATASOURCE_KEY, key);
        maps.put(DataSourceContextHolder.DATASOURCE_DRIVER, driver);
        maps.put(DataSourceContextHolder.DATASOURCE_URL,
                "jdbc:mysql://" + ip + ":" + port + "/" + datatype + "?useUnicode=true&characterEncoding=UTF-8");
        maps.put(DataSourceContextHolder.DATASOURCE_USERNAME, username);
        maps.put(DataSourceContextHolder.DATASOURCE_PASSWORD, pas);
        DataSourceContextHolder.setDBType(maps);
    }

    public void ClearDataSourceSwitch() {
        DataSourceContextHolder.clearDBType();
    }
}
